package com.example.servlet;

import com.example.service.UserService;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import java.io.IOException;

/**
 * 用户Servlet控制器
 * 处理用户登录和登出请求
 */
@WebServlet("/UserServlet")
public class UserServlet extends HttpServlet {

    private UserService userService;

    @Override
    public void init() throws ServletException {
        super.init();
        this.userService = new UserService();
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");

        String action = request.getParameter("action");

        if ("login".equals(action)) {
            handleLogin(request, response);
        } else if ("logout".equals(action)) {
            handleLogout(request, response);
        } else {
            // 默认跳转到登录页面
            response.sendRedirect("login.jsp");
        }
    }

    /**
     * 处理登录请求
     */
    private void handleLogin(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        String username = request.getParameter("username");
        String password = request.getParameter("password");

        // 输入校验
        if (username == null || username.trim().isEmpty() ||
                password == null || password.trim().isEmpty()) {
            request.setAttribute("errorMessage", "用户名和密码不能为空！");
            request.getRequestDispatcher("login.jsp").forward(request, response);
            return;
        }

        try {
            // 验证用户登录
            if (userService.login(username, password)) {
                // 登录成功，将用户名存储到session中
                HttpSession session = request.getSession();
                session.setAttribute("username", username);

                // 重定向到欢迎页面
                response.sendRedirect("welcome.jsp");
            } else {
                // 登录失败，设置错误信息并转发回登录页面
                request.setAttribute("errorMessage", "用户名或密码错误！");
                request.getRequestDispatcher("login.jsp").forward(request, response);
            }
        } catch (Exception e) {
            // 记录异常日志（实际项目中应使用 SLF4J 或 Log4j）
            e.printStackTrace();
            request.setAttribute("errorMessage", "系统繁忙，请稍后重试！");
            request.getRequestDispatcher("login.jsp").forward(request, response);
        }
    }

    /**
     * 处理登出请求
     */
    private void handleLogout(HttpServletRequest request, HttpServletResponse response)
            throws IOException {

        // 清除session
        HttpSession session = request.getSession(false);
        if (session != null) {
            session.invalidate();
        }

        // 重定向到登录页面
        response.sendRedirect("login.jsp");
    }
}
